package top.stacktrace.gateway.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import top.stacktrace.account.domain.LoginVo;
import top.stacktrace.gateway.config.auth.AuthException;
import top.stacktrace.gateway.config.auth.Token;
import top.stacktrace.gateway.service.LoginService;
import top.stacktrace.util.Result;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

@RestController
public class GateController {
    @Autowired
    private LoginService loginService;

    @PostMapping("/login")
    public Mono<Token> login(@RequestBody LoginVo v){
        return Mono.create(monoSink -> {
            Token t = loginService.login(v);
            if(t.isAuthenticated()){
                monoSink.success(t);
            }else{
                loginService.removeToken(t.getToken());
                monoSink.error(new AuthException());
            }
        }).cast(Token.class).subscribeOn(Schedulers.boundedElastic());
    }

    @PostMapping("/logout")
    public Mono<Result> logout(@RequestHeader long userid){
        loginService.removeUserToken(userid);
        return Mono.just(Result.ok(""));
    }
}
